package com.example.action;

import com.example.bean.User;
import com.example.service.UserService;
import com.example.util.UUIDUtils;
import com.example.util.UploadFileUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 用户更新
 */

@WebServlet("/update")
@MultipartConfig
public class UpdateUserServlet extends HttpServlet {

    public UpdateUserServlet() {
        super();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String uid = UUIDUtils.getId();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String telephone = request.getParameter("telephone");
        String d = request.getParameter("birthday");
        String sex = request.getParameter("sex");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = null;

        try {
            birthday = format.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 旧图片
        String oldphoto = request.getParameter("oldpicture");

        User user = new User();
        user.setId(uid);
        user.setUsername(username);
        user.setPassword(password);
        user.setName(name);
        user.setEmail(email);
        user.setTelephone(telephone);
        user.setBirthday(birthday);
        user.setSex(sex);
        user.setPhoto(oldphoto);

        // 上传图片
        Part part = request.getPart("picture");
        UploadFileUtil uploadFileUtil = new UploadFileUtil();
        uploadFileUtil.setPart(part);
        uploadFileUtil.setPath("d:/photo/");
        int flag = uploadFileUtil.saveFile();
        if (flag == 1) {
            user.setPhoto(uploadFileUtil.getFilename());
        }

        UserService userService = new UserService();
        int n = userService.updateUser(user);
        if (n == 1) {
            request.setAttribute("infomation","修改成功" );
        } else {
            request.setAttribute("infomation","修改失败" );
        }
        request.setAttribute("url","index");
        request.setAttribute("second",5 );
        request.getRequestDispatcher("tip.jsp").forward(request, response);
    }
}
